package com.rzico.sbl.ui.statistic

import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityBucketRecordBinding
import com.rzico.sbl.model.HandleData
import com.rzico.sbl.other.*
import com.rzico.sbl.ui.member.MemberDetailActivity
import com.rzico.sbl.ui.order.OrderDetailActivity
import com.rzico.sbl.viewmodel.StatisticCommonViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.hideSoftInput
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common_ui.base.*
import com.xinnuo.common_ui.glideExt.loadCircleImage
import com.xinnuo.common_ui.utils.showTimeRangeDialog
import com.xinnuo.slimadapter.SlimAdapter
import org.json.JSONObject

class BucketRecordActivity : BaseActivity(R.layout.activity_bucket_record) {

    private val mBinding by lazy { ActivityBucketRecordBinding.bind(getRootView()) }

    private var mKeyWord = ""
    private lateinit var mBarrelType: String
    private lateinit var mDateMode: String
    private lateinit var mBeginDate: String
    private lateinit var mEndDate: String

    override fun getViewModel() = get<StatisticCommonViewModel>()

    override fun initData() {
        setToolbarVisibility(false)

        initLayout()
        initSearch()

        mBinding.apply {
            mKeyWord.notEmpty {
                recordSearch
                    .searchEdit
                    .apply {
                        setText(this@notEmpty)
                        setSelection(text.length)
                    }
            }

            listLayout
                .swipeRefresh
                .isRefreshing = true
        }

        getData(pageNum)
    }

    private fun initLayout() {
        mBinding.listLayout.apply {
            emptyLayout.also {
                it.emptyHint.text = "暂无相关押桶记录！"
            }

            recycleList.also { view ->
                view.loadLinear(
                    refresh = swipeRefresh,
                    onRefresh = { getData(0) },
                    onLoad = {
                        if (!isLoadingMore) {
                            isLoadingMore = true
                            getData(pageNum)
                        }
                    }
                )

                view.addItemDecoration(SpaceTBDecoration(hasHeader = false))

                mAdapter = SlimAdapter.creator()
                    .register<HandleData>(R.layout.item_statistic_handle_record) { jector, bean, _ ->
                        jector.apply {
                            text(R.id.item_record_title, bean.name)
                            text(R.id.item_record_name, bean.consignee)
                            text(R.id.item_record_phone, bean.phone)
                            text(R.id.item_record_count, bean.subQuantity)
                            text(R.id.item_record_price, bean.subPrice.formatDecimal())

                            with<ImageView>(R.id.item_record_img) {
                                it.loadCircleImage(bean.memberLogo, R.mipmap.default_user)
                            }

                            with<TextView>(R.id.item_record_type) { view ->
                                view.text = bean.methodDescr

                                if (bean.method == "mortgage") {
                                    view.text =
                                        "${bean.methodDescr}${bean.adminName.ifNotEmpty { "($it)" }}"
                                }
                            }

                            clicked(R.id.item_record_img) {
                                (userRole in "1,2")
                                    .condition {
                                        startActivityEx<MemberDetailActivity>(
                                            "cardId" to bean.cardId,
                                            "memberId" to bean.memberId
                                        )
                                    }
                            }

                            clicked {
                                bean.orderSn
                                    .notEmpty {
                                        startActivityEx<OrderDetailActivity>("orderSn" to this)
                                    }
                            }
                        }
                    }
                    .attachTo(view)
            }
        }
    }

    private fun initSearch() {
        mBinding
            .recordSearch
            .apply {
                searchEdit.hint = "请输入姓名、手机号"
                searchEdit.doOnTextChanged { text, _, _, _ ->
                    text?.let {
                        searchClose.isGone = it.isEmpty()

                        if (it.isEmpty() && mKeyWord.isNotEmpty()) {
                            mKeyWord = ""
                            updateList()
                        }
                    }
                }

                searchEdit.setOnEditorActionListener { _, actionId, _ ->
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        hideSoftInput() //隐藏软键盘

                        if (searchEdit.text.isBlank()) {
                            showToast("请输入姓名、手机号")
                        } else {
                            mKeyWord = searchEdit.textTrim
                            updateList()
                        }
                    }
                    return@setOnEditorActionListener false
                }

                searchClose.oneClick { searchEdit.setText("") }
                searchHint.oneClick {
                    if (searchEdit.text.isBlank()) {
                        showToast("请输入姓名、手机号")
                    } else {
                        mKeyWord = searchEdit.textTrim
                        updateList()
                    }
                }
            }
    }

    override fun initListener() {
        mBarrelType = intent.getExtra("barrelType")
        mKeyWord = intent.getExtra("keyword")
        mDateMode = intent.getExtra("dateMode")
        mBeginDate = intent.getExtra("beginDate")
        mEndDate = intent.getExtra("endDate")

        mBinding.apply {
            getViewModel().mBarrelList[0].isChecked = false
            recordType.setTextColor(getColorEx(R.color.colorAccent))
            recordTypeArrow.setImageResource(R.mipmap.icon_member02)

            when (mBarrelType) {
                "barrel" -> {
                    recordType.text = "空桶购买"
                    getViewModel().mBarrelList[1].isChecked = true
                }

                "order" -> {
                    recordType.text = "订单买桶"
                    getViewModel().mBarrelList[2].isChecked = true
                }

                "product" -> {
                    recordType.text = "商品买桶"
                    getViewModel().mBarrelList[3].isChecked = true
                }

                "mortgage" -> {
                    recordType.text = "人工押桶"
                    getViewModel().mBarrelList[4].isChecked = true
                }

                else -> {
                    getViewModel().mBarrelList[0].isChecked = true
                    recordType.setTextColor(getColorEx(R.color.black))
                    recordTypeArrow.setImageResource(R.mipmap.icon_member01)
                }
            }

            // 今日、昨日、本周、本月、上月、本年、自定义
            when (mDateMode) {
                "1" -> {
                    recordTime.text = "今日"
                    getViewModel().mUncheckTimeList[0].isChecked = true
                }

                "2" -> {
                    recordTime.text = "昨日"
                    getViewModel().mUncheckTimeList[1].isChecked = true
                }

                "3" -> {
                    recordTime.text = "本周"
                    getViewModel().mUncheckTimeList[2].isChecked = true
                }

                "5" -> {
                    recordTime.text = "上月"
                    getViewModel().mUncheckTimeList[4].isChecked = true
                }

                "6" -> {
                    recordTime.text = "本年"
                    getViewModel().mUncheckTimeList[5].isChecked = true
                }

                "7" -> {
                    recordTime.text = "$mBeginDate ~ $mEndDate"
                    getViewModel().mUncheckTimeList[6].isChecked = true
                }

                else -> {
                    mBeginDate = getFirstDate()
                    mEndDate = getEndDate()

                    recordTime.text = "本月"
                    getViewModel().mUncheckTimeList[3].isChecked = true
                }
            }
        }

        mBinding.apply {
            recordTypeLl
                .oneClick {
                    getViewModel().showDropFilter(
                        getIContext(),
                        recordTop,
                        getViewModel().mBarrelList,
                        recordType,
                        recordTypeArrow
                    ) {
                        if (it.id.isEmpty()) {
                            recordType.setTextColor(getColorEx(R.color.black))
                            recordTypeArrow.setImageResource(R.mipmap.icon_member01)
                        } else {
                            recordType.setTextColor(getColorEx(R.color.colorAccent))
                            recordTypeArrow.setImageResource(R.mipmap.icon_member02)
                        }

                        mBarrelType = it.id
                        updateList()
                    }
                }

            recordTimeLl
                .oneClick {
                    getViewModel()
                        .showDropTimeFilter(
                            getIContext(),
                            recordTime,
                            recordTimeArrow,
                            recordTop,
                            getViewModel().mUncheckTimeList
                        ) { bean ->

                            if (bean.id != "7")
                                getViewModel()
                                    .mUncheckTimeList
                                    .last()
                                    .name = "自定义时间"

                            when (bean.id) {
                                "1" -> {
                                    mBeginDate = getTodayDate()
                                    mEndDate = getTodayDate()

                                    updateList()
                                }

                                "2" -> {
                                    mBeginDate = getBeforeDate()
                                    mEndDate = getBeforeDate()

                                    updateList()
                                }

                                "3" -> {
                                    mBeginDate = getMondayDate()
                                    mEndDate = getSundayDate()

                                    updateList()
                                }

                                "4" -> {
                                    mBeginDate = getFirstDate()
                                    mEndDate = getEndDate()

                                    updateList()
                                }

                                "5" -> {
                                    mBeginDate = getBeforeFirstDate()
                                    mEndDate = getBeforeEndDate()

                                    updateList()
                                }

                                "6" -> {
                                    mBeginDate = getYearFirstDate()
                                    mEndDate = getYearEndDate()

                                    updateList()
                                }

                                "7" -> {
                                    showTimeRangeDialog(
                                        isCurrentDate = true,
                                        isAfterLimited = true,
                                        onResult = { start, end ->
                                            getViewModel()
                                                .mUncheckTimeList
                                                .forEach { it.isChecked = false }

                                            getViewModel()
                                                .mUncheckTimeList
                                                .last()
                                                .isChecked = true

                                            mBeginDate = start
                                            mEndDate = end
                                            bean.name = "$mBeginDate ~ $mEndDate"
                                            recordTime.text = bean.name

                                            updateList()
                                        }
                                    )
                                }
                            }
                        }
                }
        }

        getViewModel()
            .mRecordEvent
            .observe(this) {
                val obj = JSONObject(it).optJSONObject("data") ?: JSONObject()

                mBinding.apply {
                    recordCount.text = obj.optNotEmpty("subQuantity", "0")
                    recordMoney.text = obj.optNotNull("subPrice").formatDecimal()
                }
            }
    }

    /**
     * 押桶记录列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        // 押桶记录合计
        getViewModel()
            .recordTotal(
                keyWord = mKeyWord,
                barrelId = intent.getExtra("barrelId"),
                method = mBarrelType,
                beginDate = mBeginDate,
                endDate = mEndDate
            )

        // 押桶记录列表
        getViewModel()
            .handleRecord(
                page = index,
                keyWord = mKeyWord,
                barrelId = intent.getExtra("barrelId"),
                method = mBarrelType,
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = {
                    mList.apply {
                        if (index == 0) {
                            clear()
                            pageNum = 0
                        }
                        addItems(it)
                        if (it.count() > 0) pageNum++
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        if (mList.isNotEmpty()) {
            mList.clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}